package com.sj.purchase.modules.purchase.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sj.purchase.util.HttpUtil;
import org.apache.commons.lang3.time.DateFormatUtils;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class MoveService {

	private static String DATA_FORMAT_STR = "yyyy-MM-dd";

	@Value("${sj.ecwms}")
	private String url;

	public JSONObject getList(Date startTime, Date endTime, Date submitStartTime, Date submitEndTime, String moveKey,
			String moveType, String referNo, String warehouseNo, String storerNo, String codeValue, String sourceZoneNo,
			String aimZoneNo, int pageNum, int pageSize, boolean isExcel) {
		try {
			StringBuffer stringBuffer = new StringBuffer();
			stringBuffer.append(url+"gyMove?startTime=" + DateFormatUtils.format(startTime,DATA_FORMAT_STR) + "&endTime="
					+ DateFormatUtils.format(endTime,DATA_FORMAT_STR));
			if (submitStartTime != null && submitEndTime != null) {
				stringBuffer.append("&submitStartTime=" + DateFormatUtils.format(submitStartTime,DATA_FORMAT_STR) + "&submitEndTime="
						+ DateFormatUtils.format(submitEndTime,DATA_FORMAT_STR));
			}
			if (isNonEmpty(moveKey)) {
				stringBuffer.append("&moveKey=" + moveKey);
			}
			if (isNonEmpty(moveType)) {
				stringBuffer.append("&moveType=" + moveType);
			}
			if (isNonEmpty(referNo)) {
				stringBuffer.append("&referNo=" + referNo);
			}
			if (isNonEmpty(storerNo)) {
				stringBuffer.append("&storerNo=" + storerNo);
			}
			if (isNonEmpty(codeValue)) {
				stringBuffer.append("&codeValue=" + codeValue);
			}
			if (isNonEmpty(warehouseNo)) {
				stringBuffer.append("&warehouseNo=" + warehouseNo);
			}
			if (isNonEmpty(sourceZoneNo)) {
				stringBuffer.append("&sourceZoneNo=" + sourceZoneNo);
			}
			if (isNonEmpty(aimZoneNo)) {
				stringBuffer.append("&aimZoneNo=" + aimZoneNo);
			}
			if (pageNum == 0) {
				stringBuffer.append("&pageNum=1");
			} else {
				stringBuffer.append("&pageNum=" + pageNum);
			}
			stringBuffer.append("&pageSize=" + pageSize);
			if (isExcel) {
				stringBuffer.append("&isPaging=" + false);
			}
			HttpGet get = HttpUtil.get(stringBuffer.toString());
			CloseableHttpClient httpclient = HttpUtil.httpclient();
			HttpResponse response = httpclient.execute(get);
			String jsonStr = EntityUtils.toString(response.getEntity(), "utf-8");
			HttpUtil.close(httpclient);
			JSONObject jsonObject = JSON.parseObject(jsonStr);
			return jsonObject;
		} catch (Exception e) {
			e.printStackTrace();
			return null;
		}
	}

	public static boolean isNonEmpty(String str) {
		return str == null ? false : str.trim().length() > 0;

	}
}
